# 构建阶段
FROM golang:1.21-alpine AS builder

WORKDIR /app

# 复制 go mod 文件
COPY go.mod go.sum ./

# 下载依赖
RUN go mod download

# 复制源代码
COPY . .

# 构建应用
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# 运行阶段
FROM alpine:latest

# 安装 ca-certificates
RUN apk --no-cache add ca-certificates

# 创建非 root 用户
RUN addgroup -g 1000 appgroup && \
    adduser -u 1000 -G appgroup -s /bin/sh -D appuser

# 创建应用目录并设置权限
RUN mkdir -p /app && chown -R appuser:appgroup /app

WORKDIR /app

# 从构建阶段复制二进制文件并设置权限
COPY --from=builder /app/main .
RUN chmod +x main && chown appuser:appgroup main

# 切换到非 root 用户
USER appuser

# 运行应用
CMD ["./main"]
